<template>
  <div class="view-fill">
    <div class="app-container-flex" v-show="!detailInfo.visible">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>借用详情</p>
          </div>
          <div class="model-panel-body borrowing-box">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addAsset>
                <el-button :disabled="props.orderId" @click="addAsset()"
                  >添加设备</el-button
                >
              </template>
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除设备</el-button
                >
              </template>
            </PageFilter>
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-btnSlotArr>
                <el-form
                  :inline="true"
                  :model="formFilter"
                  class="demo-form-inline"
                >
                  <el-form-item label="借用部门：" labelWidth="80px">
                    <el-input
                      v-model="formFilter.borrowDeptName"
                      class="not-mongolia"
                      type="input"
                      :required="true"
                      :disabled="true"
                      :placeholder="'请选择借用部门'"
                    >
                      <template #append>
                        <el-icon @click="checkDeptName"><MoreFilled /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="借用人：">
                    <el-input
                      v-model="formFilter.borrowUserName"
                      class="not-mongolia"
                      type="input"
                      :required="true"
                      :disabled="true"
                      :placeholder="'请选择借用人'"
                    >
                      <template #append>
                        <el-icon @click="checkUserName"><MoreFilled /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="借用时间: ">
                    <el-date-picker
                      v-model="formFilter.borrowTime"
                      type="datetime"
                      value-format="YYYY-MM-DD HH:mm"
                      :disabled="!canSettingAsset"
                      placeholder="选择日期"
                      @change="
                        (val) => {
                          changeForm(val)
                        }
                      "
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="预计归还时间: ">
                    <el-date-picker
                      v-model="formFilter.preReturnTime"
                      type="datetime"
                      value-format="YYYY-MM-DD HH:mm"
                      :disabled="!canSettingAsset"
                      placeholder="选择日期"
                      :disabled-date="
                        (time) => {
                          return formFilter?.disableDate(time)
                        }
                      "
                      :disabled-hours="
                        () => {
                          return formFilter?.disabledHour()
                        }
                      "
                      :disabled-minutes="
                        () => {
                          return formFilter?.disabledMinute()
                        }
                      "
                      :disabled-seconds="
                        () => {
                          return formFilter?.disabledSecond()
                        }
                      "
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      :disabled="!canSettingAsset"
                      type="primary"
                      @click="allSetting"
                      >一键设置</el-button
                    >
                  </el-form-item>
                </el-form>
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isRowClickSelect="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showProductDetail(scope.row)"
                    >
                      {{ scope.row.assetName || '-' }}
                    </span>
                  </template>
                  <template v-slot:col-borrowDeptName="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.borrowDeptName`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择借用部门',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                    >
                      <el-input
                        v-model="scope.row.borrowDeptName"
                        class="not-mongolia"
                        type="input"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.borrowDeptName`,
                            'tableForm'
                          )
                        "
                        :required="true"
                        :disabled="true"
                        :placeholder="'请选择借用部门'"
                      >
                        <template #append>
                          <el-icon @click="checkDeptNameRow(scope.row)"
                            ><MoreFilled
                          /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-borrowUserName="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.borrowUserName`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择借用人',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                    >
                      <el-input
                        v-model="scope.row.borrowUserName"
                        class="not-mongolia"
                        type="input"
                        :required="true"
                        :disabled="true"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.borrowUserName`,
                            'tableForm'
                          )
                        "
                        :placeholder="'请选择借用人'"
                      >
                        <template #append>
                          <el-icon @click="checkUserNameRow(scope.row)"
                            ><MoreFilled
                          /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-borrowTime="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.borrowTime`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择借用时间',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                    >
                      <el-date-picker
                        v-model="scope.row.borrowTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.borrowTime`,
                            'tableForm'
                          )
                        "
                        @change="
                          (val) => {
                            changeRow(val, scope.row)
                          }
                        "
                        placeholder="选择日期"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </template>
                  <template v-slot:col-preReturnTime="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.preReturnTime`"
                    >
                      <el-date-picker
                        v-model="scope.row.preReturnTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.preReturnTime`,
                            'tableForm'
                          )
                        "
                        placeholder="选择日期"
                        :disabled-date="
                          (time) => {
                            return scope.row?.disableDate(time)
                          }
                        "
                        :disabled-hours="
                          () => {
                            return scope.row?.disabledHour()
                          }
                        "
                        :disabled-minutes="
                          () => {
                            return scope.row?.disabledMinute()
                          }
                        "
                        :disabled-seconds="
                          () => {
                            return scope.row?.disabledSecond()
                          }
                        "
                      />
                    </el-form-item>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加资产 -->
    <SelectAsset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :api="getCanBorrowPage"
      table-key="assetCanBorrowSelectList-com.slip.spd.entity.vo.asset.useManage.AssetCanBorrowVO"
      :check-box="selectAssetInfo.checkBox"
      :highlightRow="true"
      @callback="callBackAsset"
    />
    <SelectUsers
      v-if="selectUserInfo.visible"
      v-model:showDialog="selectUserInfo.visible"
      :query="selectUserInfo.query"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectUserCallBack"
    />
    <!-- 选择部门 -->
    <SelectDept
      v-if="useDeptInfo.visible"
      v-model:show-dialog="useDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="useDeptInfo.query"
      :save-empty="true"
      @callback="callbackUseDept"
    />
    <!-- 详情页 -->
    <assetCard-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="equipmentBorrowingRecordModify">
import {
  createBorrowRecord,
  getBorrowRecordById,
  updateBorrowRecordPut,
  getCanBorrowPage,
} from '@/api/asset'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { getCustomizeSetting } from '@/api/customize'
import { getRrgUserList } from '@/api/base.js'
import moment from 'moment'
import {
  disableDate,
  disabledHour,
  disabledMinute,
  disabledSecond,
  setDisDate,
} from '@/common/js/base'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])

const useDeptInfo = ref({
  visible: false,
  query: {
    status: 1,
    deptAuth: 'id',
  },
})
//明细相关
const detailInfo = ref({
  visible: false,
  title: '资产档案明细',
  id: '',
})
const selectUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: { deptId: '' },
})

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addAsset' },
    { type: 'slot', value: 'removeAsset' },
    { type: 'slot', value: 'btnSlotArr' },
  ],
})
// 一键设置表单
const formFilter = ref({
  borrowTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
})
const ids = ref('')
const currentRow = ref(formFilter.value)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: function (row) {
          return !props.orderId
        },
      },
    ],
  },
})
const selectAssetInfo = ref({
  visible: false,
  checkBox: true,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetId: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
    },
    queryParams: { assetBorrowRecordFilter: 0 },
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    setIds()
  },
  {
    deep: true,
  }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length && !props.orderId
})
const canSettingAsset = computed(() => {
  return tableInfo.value.data.length
})
onMounted(() => {})
setData()
formFilter.value.disableDate = disableDate
formFilter.value.disabledHour = disabledHour
formFilter.value.disabledMinute = disabledMinute
formFilter.value.disabledSecond = disabledSecond
function setData() {
  let obj = {
    borrowDeptName: {
      label: '借用部门',
      value: 'borrowDeptName',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
    borrowUserName: {
      label: '借用人',
      value: 'borrowUserName',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
    borrowTime: {
      label: '借用时间',
      value: 'borrowTime',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
    preReturnTime: {
      label: '预计归还时间',
      value: 'preReturnTime',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  console.log(
    proxy.$store.state.user.userInfo,
    'proxy.$store.state.user.userInfo'
  )
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function setIds() {
  ids.value = tableInfo.value.data.map((element) => {
    return element.assetId
  })
  selectAssetInfo.value.query.queryMap.assetId.value = ids.value.join(',')
}
function showProductDetail(row) {
  sessionStorage.setItem('storeRowId', row.assetId)
  detailInfo.value.visible = true
  detailInfo.value.title = '资产详情'
  detailInfo.value.id = row.assetId
}
function checkDeptName() {
  currentRow.value = formFilter.value
  useDeptInfo.value.visible = true
}
function checkUserName() {
  currentRow.value = formFilter.value
  selectUserInfo.value.visible = true
}
function checkDeptNameRow(row) {
  currentRow.value = row
  useDeptInfo.value.visible = true
}
function checkUserNameRow(row) {
  if (!row.borrowDeptName) {
    proxy.$message({
      type: 'warning',
      showClose: true,
      message: '请先选择借用部门',
    })
    return
  }
  currentRow.value = row
  selectUserInfo.value.visible = true
}
function allSetting() {
  const obj = formFilter.value
  tableInfo.value.data.forEach((item) => {
    for (let k in obj) {
      if (obj[k] || obj[k] == 0) {
        item[k] = obj[k]
      }
    }
  })
  proxy.$refs.tableForm.clearValidate()
}
function callbackUseDept(row) {
  if (row) {
    currentRow.value.borrowDeptId = row.id
    currentRow.value.borrowDeptName = row.name
    selectUserInfo.value.query.deptId = row.id
  } else {
    currentRow.value.borrowDeptId = ''
    currentRow.value.borrowDeptName = ''
  }
}
function selectUserCallBack(row) {
  if (row) {
    currentRow.value.borrowUser = row.id
    currentRow.value.borrowUserName = row.name
  } else {
    currentRow.value.borrowUser = ''
    currentRow.value.borrowUserName = ''
  }
}
function getMain() {
  getBorrowRecordById(props.orderId).then((res) => {
    if (res && res.success) {
      setDefaultDate(res.data)
      tableInfo.value.data = [res.data]
    }
  })
}
function changeForm(val) {
  formFilter.value.preReturnTime = ''
  setDisDate(val, formFilter.value)
}
function changeRow(val, row) {
  row.preReturnTime = ''
  setDisDate(val, row)
}
// 设置默认禁用当前时间之前日期
function setDefaultDate(data) {
  data.disableDate = disableDate
  data.disabledHour = disabledHour
  data.disabledMinute = disabledMinute
  data.disabledSecond = disabledSecond
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function save() {
  if (tableInfo.value.data && tableInfo.value.data.length === 0) {
    proxy.$message.warning('请添加设备！')
    return
  }
  proxy.$refs.tableForm.validate((valid2) => {
    if (valid2) {
      const api = props.orderId ? updateBorrowRecordPut : createBorrowRecord
      let data = props.orderId ? tableInfo.value.data[0] : tableInfo.value.data
      api(data).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          proxy.$emit('returnModify', false)
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}

//选择资产
function addAsset() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  selectAssetInfo.value.checkBox = true
  selectAssetInfo.value.query.queryParams.analysisPlanIdNotIn = props.orderId
  selectAssetInfo.value.visible = true
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.canBorrowId = item.id
    setDefaultDate(item)
  })
  tableInfo.value.data = data.concat(tableInfo.value.data)
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetBorrowRecordAddList-com.slip.spd.entity.vo.asset.useManage.AssetCanBorrowVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      if (props.orderId) {
        getMain()
      }
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
:deep(.model-panel-body) .filter-item {
  .el-form-item--default.el-form-item {
    margin-top: 6px;
    margin-bottom: 6px;
  }
}
.borrowing-box {
  .page-filter {
    .filter-item:nth-child(3) {
      width: 100% !important;
    }
  }
}
</style>
